package com.tzvtc.server.account.service;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWTUtil;
import com.tzvtc.server.account.bean.AccountBean;
import com.tzvtc.server.account.mapper.AccountMapper;
import com.tzvtc.server.commons.exception.NormalException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Slf4j
@Service
public class AccountService {

    @Resource
    private AccountMapper accountMapper;


    public String login(AccountBean accountBean){log.debug("用户登录,检查参数完整性");
       if (accountBean.getUsername()==null || "".equals(accountBean.getUsername().trim())){
          throw new NormalException("用户名不能为空");
       }
       if (accountBean.getPassword()==null || "".equals(accountBean.getPassword().trim())){
          throw new NormalException("密码不能为空");
       }

       log.debug("用户登录，参数转换");
       accountBean.setUsername(accountBean.getUsername().trim());
       accountBean.setPassword(accountBean.getPassword().trim());

       log.debug("用户登录，根据用户名查询信息");
       AccountBean resultBean = accountMapper.selectOne(accountBean);
       if (resultBean==null){
          throw new NormalException("用户名密码错误");
       }

       log.debug("用户登录，密码对比");
       String password = DigestUtil.md5Hex(accountBean.getPassword());
       if (!resultBean.getPassword().equals(password)){
          throw new NormalException("用户名密码错误");
       }

       HashMap<String,Object> map = new HashMap<>();
       map.put("id",resultBean.getId());

       return JWTUtil.createToken(map, "1234".getBytes());
    }

    public static void main(String[] args) {
        String str = "hanchun123";
        String newStr = DigestUtil.md5Hex(str);
        System.out.println(newStr);
    }

}
